import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入浏览器显示进度条
import nprogress from 'nprogress'
import Login from '../views/Login.vue'
import Admin from '../views/Admin.vue'

// 导入页面路由组件
import Index from '../components/admin/Index.vue'
import AddArt from '../components/article/AddArt.vue'
import ArtList from '../components/article/ArtList.vue'
import CateList from '../components/category/CateList.vue'
import UserList from '../components/user/UserList.vue'
import NotfoundError from '../components/admin/NotfoundError.vue'
import JiJinList from '../components/JiJinList'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/',
    redirect: '/admin'
  },
  {
    path: '/admin',
    name: 'admin',
    redirect: '/admin/index',
    component: Admin,
    meta: {
      title: '后台管理'
    },
    children: [
      { path: 'index', meta: { title: '仪表盘' }, component: Index },
      { path: 'addart', meta: { title: '添加文章' }, component: AddArt },
      // 创建编辑路由，利用props传参数
      { path: 'addart/:id', meta: { title: '编辑文章' }, component: AddArt, props: true },
      { path: 'artlist', meta: { title: '文章列表' }, component: ArtList },
      { path: 'catelist', meta: { title: '分类列表' }, component: CateList },
      { path: 'userlist', meta: { title: '用户列表' }, component: UserList },
      { path: 'jijinlist', meta: { title: '自选基金列表' }, component: JiJinList }
    ]
  },
  {
    path: '/*',
    hidden: true,
    name: 'error',
    meta: {
      title: 'NotfoundError'
    },
    component: NotfoundError
  }
]

const router = new VueRouter({
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 获取token
  const token = window.sessionStorage.getItem('token')
  // 访问 /login 直接放行
  if (to.path === '/login') return next()
  // 如果木有token，访问其他页面则直接返回 /login
  if (!token) {
    next('/login')
  } else {
    // 浏览器进度条
    nprogress.start()
    //  to.meta 设置浏览器 title
    if (to.meta && to.meta.title) { document.title = to.meta.title }
    next()
  }
})

router.afterEach(() => {
  nprogress.done()
})

export default router
